<template>
  <view class="uni-file-picker">
    <!-- 上传按钮区域 -->
    <view 
      v-if="fileList.length < limit"
      class="upload-area" 
      @click="selectFile"
    >
      <slot></slot>
    </view>
    
    <!-- 已选择的文件列表 -->
    <view v-if="fileList.length > 0" class="file-list">
      <view 
        v-for="(file, index) in fileList" 
        :key="index"
        class="file-item"
      >
        <view class="file-icon" :style="{ backgroundColor: getFileTypeColor(file.extname) }">
          <text class="file-type">{{ getFileTypeText(file.extname) }}</text>
        </view>
        <view class="file-info">
          <view class="file-name">{{ file.name }}</view>
          <view class="file-size">{{ formatFileSize(file.size) }}</view>
        </view>
        <view class="file-actions">
          <view class="delete-btn" @click.stop="deleteFile(index)">
            <view class="delete-icon">×</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'UniFilePicker',
  props: {
    fileMediatype: {
      type: String,
      default: 'all'
    },
    fileExtname: {
      type: Array,
      default: () => []
    },
    limit: {
      type: Number,
      default: 9
    },
    value: {
      type: Array,
      default: () => []
    },
    autoUpload: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: []
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.fileList = newVal || [];
      },
      immediate: true
    }
  },
  methods: {
    // 触发选择文件事件
    selectFile() {
      console.log('uni-file-picker clicked, selecting file...');
      
      // 根据平台选择不同的文件选择方式
      // #ifdef H5
      this.selectFileH5();
      // #endif
      
      // #ifdef MP
      this.selectFileMP();
      // #endif
      
      // #ifdef APP-PLUS
      this.selectFileApp();
      // #endif
    },
    
    // H5端文件选择
    selectFileH5() {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = this.fileExtname.map(ext => `.${ext}`).join(',');
      input.multiple = this.limit > 1;
      input.onchange = (e) => {
        const files = Array.from(e.target.files);
        this.handleFiles(files);
      };
      input.click();
    },
    
    // 小程序端文件选择
    selectFileMP() {
      if (this.fileMediatype === 'image') {
        uni.chooseImage({
          count: this.limit - this.fileList.length,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            this.handleFiles(res.tempFiles);
          },
          fail: (err) => {
            console.error('选择图片失败:', err);
            uni.showToast({
              icon: 'none',
              title: '选择图片失败'
            });
          }
        });
      } else {
        uni.chooseMessageFile({
          count: this.limit - this.fileList.length,
          type: 'file',
          extension: this.fileExtname,
          success: (res) => {
            this.handleFiles(res.tempFiles);
          },
          fail: (err) => {
            console.error('选择文件失败:', err);
            uni.showToast({
              icon: 'none',
              title: '选择文件失败'
            });
          }
        });
      }
    },
    
    // App端文件选择
    selectFileApp() {
      if (this.fileMediatype === 'image') {
        uni.chooseImage({
          count: this.limit - this.fileList.length,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            this.handleFiles(res.tempFiles);
          },
          fail: (err) => {
            console.error('选择图片失败:', err);
            uni.showToast({
              icon: 'none',
              title: '选择图片失败'
            });
          }
        });
      } else {
        uni.chooseFile({
          count: this.limit - this.fileList.length,
          extension: this.fileExtname.map(ext => `.${ext}`),
          success: (res) => {
            this.handleFiles(res.tempFiles);
          },
          fail: (err) => {
            console.error('选择文件失败:', err);
            uni.showToast({
              icon: 'none',
              title: '选择文件失败'
            });
          }
        });
      }
    },
    
    // 处理选择的文件
    handleFiles(files) {
      if (!files || files.length === 0) return;
      
      console.log('处理选择的文件:', files);
      
      const newFiles = files.map(file => {
        return {
          name: file.name || file.fileName || '未知文件',
          size: file.size || file.fileSize || 0,
          path: file.path || file.tempFilePath || file.path,
          extname: this.getFileExtname(file.name || file.fileName),
          file: file
        };
      });
      
      // 检查文件数量限制
      if (this.fileList.length + newFiles.length > this.limit) {
        uni.showToast({
          icon: 'none',
          title: `最多只能选择${this.limit}个文件`
        });
        return;
      }
      
      // 添加到文件列表
      this.fileList.push(...newFiles);
      this.$emit('input', this.fileList);
      this.$emit('select', { tempFiles: newFiles });
      
    //   console.log('文件已添加到列表:', this.fileList);
    },
    
    // 获取文件扩展名
    getFileExtname(filename) {
      if (!filename) return '';
      const lastDotIndex = filename.lastIndexOf('.');
      return lastDotIndex > -1 ? filename.slice(lastDotIndex + 1).toLowerCase() : '';
    },
    
    // 获取文件类型显示文本
    getFileTypeText(extname) {
      const typeMap = {
        'pdf': 'PDF',
        'doc': 'W',
        'docx': 'W',
        'xls': 'X',
        'xlsx': 'X',
        'ppt': 'P',
        'pptx': 'P'
      };
      return typeMap[extname] || extname.toUpperCase();
    },
    
    // 获取文件类型图标颜色
    getFileTypeColor(extname) {
      const colorMap = {
        'pdf': '#ef4444',
        'doc': '#3b82f6',
        'docx': '#3b82f6',
        'xls': '#10b981',
        'xlsx': '#10b981',
        'ppt': '#f59e0b',
        'pptx': '#f59e0b'
      };
      return colorMap[extname] || '#6b7280';
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return '0 B';
      
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    // 删除文件
    deleteFile(index) {
      const deletedFile = this.fileList[index];
      this.fileList.splice(index, 1);
      this.$emit('input', this.fileList);
      this.$emit('delete', { index, tempFile: deletedFile });
      
      uni.showToast({
        icon: 'success',
        title: '文件已删除'
      });
    }
  }
}
</script>

<style scoped>
.uni-file-picker {
  width: 100%;
}

.upload-area {
  cursor: pointer;
  margin-bottom: 16rpx;
}

.upload-area:active {
  opacity: 0.8;
}

.file-list {
  width: 100%;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8rpx 12rpx;
  margin-bottom: 8rpx;
  background-color: #ffffff;
  border: 1rpx solid #e5e7eb;
  border-radius: 8rpx;
  min-height: 56rpx;
}

.file-icon {
  width: 36rpx;
  height: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6rpx;
  margin-right: 12rpx;
  flex-shrink: 0;
}

.file-type {
  color: #ffffff;
  font-size: 16rpx;
  font-weight: bold;
  line-height: 1;
}

.file-info {
  flex: 1;
  margin-right: 12rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.file-name {
  font-size: 24rpx;
  color: #374151;
  margin-bottom: 2rpx;
  word-break: break-all;
  line-height: 1.2;
  display: block;
}

.file-size {
  font-size: 20rpx;
  color: #6b7280;
  line-height: 1.2;
  display: block;
}

.file-actions {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.delete-btn {
  width: 28rpx;
  height: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.delete-icon {
  color: #9ca3af;
  font-size: 18rpx;
  font-weight: bold;
  line-height: 1;
}

.delete-btn:active {
  opacity: 0.7;
}
</style> 